package com.wjw.spring5.mapper.impl;

import com.wjw.spring5.entity.User;
import com.wjw.spring5.mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author wjw
 * @date 2021年11月05日 19:39
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int addUser(User user) {
        String sql = "insert into t_user(name) values(?)";
        Object[] args = {user.getName()};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int updateUser(User user) {
        String sql = "update t_user set name = ? where id = ?";
        Object[] args = {user.getName(), user.getId()};
        // 参数的顺序要和占位的顺序一致
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int deleteUser(Integer id) {
        String sql = "delete from t_user where id = ?";
        Object[] args = {id};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int queryValue() {
        String sql = "select count(*) from t_user";
        Object[] args = {};
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    @Override
    public User queryUser(Integer id) {
        String sql = "select id, name from t_user where id = ?";
        Object[] args = {id};
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class), args);
    }

    @Override
    public List<User> queryAllUser() {
        String sql = "select id, name from t_user";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
    }

    @Override
    public int[] batchAdd(List<Object[]> batchArgs) {
        String sql = "insert into t_user(name) values(?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        return ints;
    }

    @Override
    public int[] batchUpdateUser(List<Object[]> batchArgs) {
        String sql = "update t_user set name = ? where id = ?";
        return jdbcTemplate.batchUpdate(sql, batchArgs);
    }

    @Override
    public int[] batchDelete(List<Object[]> batchArgs) {
        String sql = "delete from t_user where id = ?";
        return jdbcTemplate.batchUpdate(sql, batchArgs);
    }
}
